﻿using Ldt.DataEngine.RuleAssemble;
using LdtJudge.DataEngine.CallInterface.CommHelp;
using LdtJudge.DataEngine.Common.DateAssemble;
using LdtJudge.DataEngine.Model.DataModel.SystemtableModel;
using LdtJudge.DataEngine.Model.LogicblockServers;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;

namespace LdtJudge.DataEngine.Common.CommHelp
{
    /// <summary>
    /// 字典值查询
    /// </summary>
    public class DictionariesConver
    {
        private static string connstr = "Ldt_JudgeDocSystem";

        private static IFreeSql freeSql = FreeSQLHelp.GetFreeSQL("Ldt_JudgeDocSystem");
        /// <summary>
        /// 计算字典值内容
        /// </summary>
        /// <param name="am_code"></param>
        /// <returns></returns>
        public static string DictionaryValueName(string am_code)
        {
            Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon("Ldt_JudgeDocSystem");
            return sqlSyscom.GetDictionaryName(am_code);

        }

        private static ConcurrentDictionary<string, IDictionary<string, string>> _DictArgumentType = new ConcurrentDictionary<string, IDictionary<string, string>>();
        /// <summary>
        /// 系统参数与匹配关键词的缓存字典
        /// </summary>
        //private static IDictionary<string, string> _DicArgumentMatchWords = new Dictionary<string, string>();
        private static ConcurrentDictionary<string, string> _DicArgumentMatchWords = new ConcurrentDictionary<string, string>();
        /// <summary>
        /// 根据参数的名称，获取其对应的参数值
        /// </summary>
        /// <param name="SourceType">原始类型 sql 还是 paramter</param>
        /// <param name="SourceContent">原始内容</param>
        /// <param name="ParamValueName">默认值</param>
        /// <returns>参数值</returns>
        public static string GetArgumentValue(string SourceType, string SourceContent, string ParamValueName)
        {
            return GetArgumentValueOrName(SourceType, SourceContent, ParamValueName, true);
            //if (SourceType != "sql" && SourceType != "paramter" && SourceType != "callprogram") 
            //{
            //    return ParamValueName;
            //}

            //if (SourceType == "sql" && SourceContent != string.Empty)
            //{
            //    return GetArgumentValueBySQLType(SourceContent, ParamValueName);
            //}
            //else if (SourceType == "paramter")
            //{
            //    //return GetArgumentValueByArgumentType(SourceContent, ParamValueName);
            //    return GetArgumentObjectByArgumentType(SourceContent, ParamValueName,true);
            //}else if (SourceType== "callprogram")
            //{//这里表示调用程序中的方法进行转换数据 2018-04-02
            //    return DateTimeFormat.ConvertEntrance(SourceContent, ParamValueName);
            //}
            //return ParamValueName;
        }


        /// <summary>
        /// 根据参数的值，获取其对应的参数名
        /// </summary>
        /// <param name="SourceType">原始类型 sql 还是 paramter</param>
        /// <param name="SourceContent">原始内容</param>
        /// <param name="ParamValue">参数值</param>
        /// <returns>参数名</returns>
        public static string GetArgumentName(string SourceType, string SourceContent, string ParamValue)
        {
            return GetArgumentValueOrName(SourceType, SourceContent, ParamValue, false);
            //if (SourceType != "sql" && SourceType != "paramter")
            //{
            //    return ParamValue;
            //}

            //if (SourceType == "sql" && SourceContent != string.Empty)
            //{
            //    return GetArgumentNameBySQLType(SourceContent, ParamValue);
            //}
            //else if (SourceType == "paramter")
            //{
            //    //return GetArgumentNameByArgumentType(SourceContent, ParamValue);
            //    return GetArgumentObjectByArgumentType(SourceContent, ParamValue,false);
            //}
            //return ParamValue;
        }

        /// <summary>
        /// 根据案由ID获取字典值类型
        /// </summary>
        /// <param name="caseid">案由id</param>
        /// <returns></returns>
        public static List<SYS_ArgumentType> GetTabl_SysArgumentTypeTable(string at_code)
        {
            string sql = @"select * from SYS_ArgumentType where AT_code='" + at_code + "'";

            //Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon("Ldt_JudgeDocSystem");

            //DataTable oTb = sqlSyscom.GetDataTable(sql);

            List<SYS_ArgumentType> sYS_ArgumentTypeList = freeSql.Select<SYS_ArgumentType>().Where(a => a.AT_Code == at_code)?.ToList();
            return sYS_ArgumentTypeList;
        }
        private static string GetArgumentValueOrName(string SourceType, string SourceContent, string ParamObject, bool Isvalue)
        {
            if (SourceType != "sql" && SourceType != "paramter" && SourceType != "callprogram")
            {
                return ParamObject;
            }

            if (SourceType == "sql" && SourceContent != string.Empty)
            {
                //这里主要是判断是根据法院名称或者法院ID还是根据法院ID获取法院名称
                if (Isvalue)
                {
                    return GetArgumentValueBySQLType(SourceContent, ParamObject);
                }
                else
                {
                    return GetArgumentNameBySQLType(SourceContent, ParamObject);
                }

            }
            else if (SourceType == "paramter")
            {
                return GetArgumentObjectByArgumentType(SourceContent, ParamObject, Isvalue);

            }
            else if (SourceType == "callprogram")
            {
                //这里表示调用程序中的方法进行转换数据 2018-04-02
                return DateTimeFormat.ConvertEntrance(SourceContent, ParamObject);
            }
            return ParamObject;
        }
        /// <summary>
        /// 根据SQL语句，获取对应的参数名
        /// </summary>
        /// <param name="StrSQL">查询语句</param>
        /// <param name="fieldValue">参数名</param>
        /// <returns>参数值</returns>
        private static string GetArgumentNameBySQLType(string StrSQL, string fieldValue)
        {
            if (StrSQL == "")
            {
                return fieldValue;
            }
            if (Regex.IsMatch(StrSQL, "sys_court|sys_prosecutordept"))
            {
                string convertValue = GetCourtProsecutorNameByID(StrSQL, fieldValue);
                if (convertValue == "") return fieldValue;
                else
                {
                    return convertValue;
                }
            }
            Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon("Ldt_JudgeDocSystem");

            DataTable oTb = sqlSyscom.GetDataTable(StrSQL);
            if (oTb != null && oTb.Rows.Count > 0)
            {
                string columnName = oTb.Columns[0].ColumnName;
                DataRow[] finalArr = oTb.Select(columnName + "='" + fieldValue + "'");

                if (finalArr.Length > 0)
                    return StringAssemble.LdFormat.ObjectToString(finalArr[0][1]);
            }

            return fieldValue;
        }
        /// <summary>
        /// 获取审判机关名称
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <param name="IDValue">唯一编号</param>
        /// <returns>审判机关名称</returns>
        public static string GetCourtProsecutorNameByID(string strSQL, string IDValue)
        {
            bool isCourt = Regex.IsMatch(strSQL, "sys_court", RegexOptions.IgnoreCase);   //判断是法院还是检查院？？

            if (isCourt)
            {
                strSQL = "select CH_Name from sys_Court where (courtID='" + IDValue + "')";
                List<SYS_Court> sYS_CourtList = freeSql.Select<SYS_Court>().Where(a => a.CourtID == IDValue)?.ToList();
                if (sYS_CourtList != null)
                {
                    return sYS_CourtList[0].CH_Name;
                }
            }
            else
            {
                strSQL = "select PD_Name from  sys_prosecutordept where (PD_ID='" + IDValue + "')";

                List<SYS_ProsecutorDept> sYS_ProsecutorDeptList = freeSql.Select<SYS_ProsecutorDept>().Where(a => a.PD_ID == IDValue)?.ToList();
                if (sYS_ProsecutorDeptList != null)
                {
                    return sYS_ProsecutorDeptList[0].PD_Name;
                }
            }

            return "";
        }
        /// <summary>
        /// 根据参数的名称，获取其对应的参数值
        /// </summary>
        /// <param name="SourceType">原始类型 sql 还是 paramter</param>
        /// <param name="SourceContent">原始内容</param>
        /// <param name="ParamValueName">默认值</param>
        /// <returns>参数值</returns>
        public static string GetArgumentValue(string SourceType, string SourceContent, string ParamValueName, bool Isvalue)
        {
            if (SourceType != "sql" && SourceType != "paramter" && SourceType != "callprogram")
            {
                return ParamValueName;
            }

            if (SourceType == "sql" && SourceContent != string.Empty)
            {
                return GetArgumentValueBySQLType(SourceContent, ParamValueName);
            }
            else if (SourceType == "paramter")
            {
                return GetArgumentObjectByArgumentType(SourceContent, ParamValueName, Isvalue);
                //return "";
            }
            else if (SourceType == "callprogram")
            {//这里表示调用程序中的方法进行转换数据 2018-04-02
                return DateTimeFormat.ConvertEntrance(SourceContent, ParamValueName);
            }
            return ParamValueName;
        }
        /// <summary>
        /// 根据参数类型或者参数值获取参数值或者参数类型
        /// </summary>
        /// <param name="paramTypeCode"></param>
        /// <param name="paramObject"></param>
        /// <param name="isvalue"></param>
        /// <returns></returns>
        public static string GetArgumentObjectByArgumentType(string paramTypeCode, string paramObject, bool isvalue)
        {
            if (paramTypeCode == "")
            {
                return paramObject;
            }
            if (!_DictArgumentType.ContainsKey(paramTypeCode))
            {
                CachArgumentTypeToDict(paramTypeCode);
            }

            IDictionary<string, string> dicCurrArgument = (_DictArgumentType.ContainsKey(paramTypeCode)) ? _DictArgumentType[paramTypeCode] : null;

            if (dicCurrArgument != null)
            {
                if (isvalue)
                {//如果是判断根据参数值获取参数编号
                    if (dicCurrArgument.Values.Contains(paramObject))
                    {
                        foreach (var item in dicCurrArgument.Keys)
                        {
                            if (dicCurrArgument[item] == paramObject)
                                return item;
                        }
                    }
                }
                else
                {//根据参数编号获取参数值
                    if (dicCurrArgument.ContainsKey(paramObject))
                        return dicCurrArgument[paramObject];
                }
            }

            if (_DicArgumentMatchWords.ContainsKey(paramTypeCode))
            {
                string matchText = _DicArgumentMatchWords[paramTypeCode];
                if (isvalue)
                {
                    return GetArgumentValueByMatchWords(matchText, paramObject);
                }
                else
                {
                    return GetArgumentNameByMatchWords(matchText, paramObject);
                }
            }

            return paramObject;

        }
        /// <summary>
        /// 根据正则获取参数值
        /// </summary>
        /// <param name="matchKeyWords">匹配内容</param>
        /// <param name="paramValue">参数值</param>
        /// <returns>匹配结果</returns>
        public static string GetArgumentNameByMatchWords(string matchKeyWords, string paramValue)
        {
            string fieldValue = paramValue;
            if (matchKeyWords != string.Empty)
            {
                fieldValue = (fieldValue == string.Empty) ? "空" : fieldValue;
                string paternStr = @"(?<=(?:^|[;；])\s*{MatchKeyWord}\s*=\s*)[^\s,，;；]+";     //支持关键词的等于；
                string currPatern = paternStr.Replace("{MatchKeyWord}", fieldValue);
                string extractValue = Regex.Match(matchKeyWords, currPatern).Value; //返回匹配到的编号值！

                if (extractValue == string.Empty)
                {
                    return paramValue;
                }
                else
                {
                    return extractValue;
                }
            }
            return paramValue;
        }
        /// <summary>
        /// 查询指定的参数类型
        /// </summary>
        /// <param name="at_Code">参数类型编号</param>
        private static void CachArgumentTypeToDict(string at_Code)
        {

            IDictionary<string, string> paramArgument = new Dictionary<string, string>();
            string at_MatchKeyWords = string.Empty;
            //001.添加参数与匹配关键词的关系字典
            string strSQL1 = @"select AT_MatchKeyWord from SYS_ArgumentType where AT_Code='" + at_Code + "'";
            List<SYS_ArgumentType> sYS_ArgumentTypeList = freeSql.Select<SYS_ArgumentType>().Where(a => a.AT_Code == at_Code)?.ToList();
            if (sYS_ArgumentTypeList != null)
            {
                at_MatchKeyWords = sYS_ArgumentTypeList[0].AT_MatchKeyWord;
            }
           
            if (at_MatchKeyWords != string.Empty && !_DicArgumentMatchWords.ContainsKey(at_Code))
            {
                _DicArgumentMatchWords.AddOrUpdate(at_Code, at_MatchKeyWords, (key, returnvalue) => returnvalue = at_MatchKeyWords);
            }

            //002.添加参数类型下具体参数的字典
            string strSQL = @"select b.AM_Code,b.AM_Name from SYS_ArgumentType as a inner join SYS_Argument as b
		                on a.AT_ID=b.AT_ID where a.AT_Code='" + at_Code + "'";

            List<SYS_Argument> sYS_ArgumentList = freeSql.Select<SYS_ArgumentType, SYS_Argument>().LeftJoin((a, b) => a.AT_ID == b.AT_ID).Where((a, b) => a.AT_Code == at_Code)?.ToList((a, b) => new SYS_Argument { AM_Code = b.AM_Code, AM_Name = b.AM_Name });
            foreach (SYS_Argument oRow in sYS_ArgumentList)
            {
                string nCode = StringAssemble.LdFormat.ObjectToString(oRow.AM_Code);
                string nName = StringAssemble.LdFormat.ObjectToString(oRow.AM_Name);

                if (!paramArgument.ContainsKey(nCode))
                    paramArgument.Add(nCode, nName);
            }
            //添加参数类型下具体参数的字典
            if (!_DictArgumentType.ContainsKey(at_Code))
            {
                _DictArgumentType.AddOrUpdate(at_Code, paramArgument, (key, returnvalue) => returnvalue = paramArgument);
            }
        }

        /// <summary>
        /// 根据SQL语句，获取对应的参数值
        /// </summary>
        /// <param name="StrSQL">查询语句</param>
        /// <param name="fieldValue">参数名</param>
        /// <returns>参数值</returns>
        private static string GetArgumentValueBySQLType(string StrSQL, string fieldValue)
        {
            if (StrSQL == "" || fieldValue == "")
            {
                return fieldValue;
            }
            if (Regex.IsMatch(StrSQL, "sys_court|sys_prosecutordept"))
            {
                string convertValue = GetCourtProsecutorIDByName(StrSQL, fieldValue);
                if (convertValue == "") return fieldValue;
                else
                {
                    return convertValue;
                }
            }
            Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon(connstr);
            DataTable oTb = sqlSyscom.GetDataTable(StrSQL);
            if (oTb != null && oTb.Rows.Count > 0)
            {
                string columnName = oTb.Columns[1].ColumnName;
                DataRow[] finalArr = oTb.Select(columnName + "='" + fieldValue + "'");

                if (finalArr.Length > 0)
                    return StringAssemble.LdFormat.ObjectToString(finalArr[0][0]);
            }

            return fieldValue;
        }
        /// <summary>
        /// 获取审判机关编号
        /// </summary>
        /// <param name="paramsql">查询语句</param>
        /// <param name="nameValue">值</param>
        /// <returns>审判机关编号</returns>
        public static string GetCourtProsecutorIDByName(string paramsql, string nameValue)
        {
            if (nameValue.Equals("人民法院"))
            {//20180411 修改前置分析，如果文书中的法院是人民法院，则不进行转法院ID
                return null;
            }

            bool isCourt = Regex.IsMatch(paramsql, "sys_court", RegexOptions.IgnoreCase);   //判断是法院还是检查院？？
            string province = RuleParseClass.GetParseRegCodeList("CourtIDSplitA1", new List<string> { nameValue })[0];
            string city = RuleParseClass.GetParseRegCodeList("CourtIDSplitA2", new List<string> { nameValue })[0];
            string town = RuleParseClass.GetParseRegCodeList("CourtIDSplitA3", new List<string> { nameValue })[0];
            string postStr = RuleParseClass.GetParseRegCodeList("CourtIDSplitA4", new List<string> { nameValue })[0];
            StringBuilder strSQL = new StringBuilder();
            if (isCourt)
            {
                // strSQL.Append("select courtID,CH_Name from sys_Court where (1=1)");
                strSQL.Append("(1=1) ");
                if (province != string.Empty) strSQL.Append("and (ch_Province='" + province + "')");
                if (city != string.Empty) strSQL.Append("and (ch_City='" + city + "' or ch_Province='" + city + "')");
                if (town != string.Empty) strSQL.Append("and (ch_CountyAndDistrict='" + town + "')");
                if (postStr != string.Empty) strSQL.Append("and (CH_Suffix='" + postStr + "')");
                List<SYS_Court> sYS_CourtList = freeSql.Select<SYS_Court>().Where(strSQL.ToString())?.ToList();
                if (sYS_CourtList != null)
                {
                    return sYS_CourtList[0].CourtID;
                }
            }
            else
            {
                strSQL.Append("(1=1) ");
                //strSQL.Append("select PD_ID,PD_Name from  sys_prosecutordept where (1=1)");
                if (province != string.Empty) strSQL.Append("and (PD_Province='" + province + "')");
                if (city != string.Empty) strSQL.Append("and (PD_City='" + city + "' or PD_Province='" + city + "')");
                if (town != string.Empty) strSQL.Append("and (PD_CountyAndDistrict='" + town + "')");
                if (postStr != string.Empty) strSQL.Append("and (PD_Suffix='" + postStr + "')");

                List<SYS_ProsecutorDept> sYS_CourtList = freeSql.Select<SYS_ProsecutorDept>().Where(strSQL.ToString())?.ToList();
                if (sYS_CourtList != null)
                {
                    return sYS_CourtList[0].PD_ID;
                }
            }


            if (isCourt)
            {
                string sqlstr = "select courtID,CH_Name from sys_Court where CH_ShortName like '%" + nameValue + "%'";
                List<SYS_Court> sYS_CourtList = freeSql.Select<SYS_Court>().Where(a => a.CH_ShortName.IndexOf(nameValue) > -1)?.ToList();
                if (sYS_CourtList != null)
                {
                    return sYS_CourtList[0].CourtID;
                }
            }
            else
            {
                string sqlstr = "select PD_ID,PD_Name from  sys_prosecutordept  where PD_ShortName like '%" + nameValue + "%'";
                //ocom = oBase.GetSqlStringCommand(sqlstr);
                //resultObj = oBase.ExecuteScalar(ocom);
                List<SYS_ProsecutorDept> sYS_CourtList = freeSql.Select<SYS_ProsecutorDept>().Where(a => a.PD_ShortName.IndexOf(nameValue) > -1)?.ToList();
                if (sYS_CourtList != null)
                {
                    return sYS_CourtList[0].PD_ID;
                }
            }

            return "";
        }


        /// <summary>
        /// 获取字典值
        /// </summary>
        /// <param name="at_Code">字典CODE</param>
        /// <param name="at_Name">字典内容</param>
        /// <returns></returns>
        //public static string DictionaryValue(string at_Code, EntityResultItem at_Name)
        //{
        //    string value = "";
        //    if (at_Name!=null)
        //    {
        //        if (at_Name.Key.IndexOf("_") > -1)
        //        {
        //            value = at_Name.Key.Split('_')[at_Name.Key.Split('_').Length - 1];
        //        }
        //        else
        //        {
        //            Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon(connstr);
        //            DataTable dataDictionary = sqlSyscom.GetDictionaryIdList(at_Code);
        //            DataRow[] rows = dataDictionary.Select("am_name='" + at_Name + "'");
        //            if (rows.Length > 0)
        //            {
        //                value = rows[0]["AM_Code"].ToString();
        //            }
        //            else
        //            {
        //                string reg = sqlSyscom.GetDictionaryWordReg(at_Code);

        //                value = GetArgumentValueByMatchWords(reg, at_Name.Content);
        //            }
        //        }
        //    }
        //    return value;
        //}

        public static string DictionaryValue(string at_Name,string code="")
        {
            if (string.IsNullOrEmpty(code))
            {
                code = "SuitDegreeID";
            }
            CachArgumentTypeToDict(code);

            string vlaue = GetArgumentObjectByArgumentType(code, at_Name, true);
            //Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon(connstr);
            //List<SYS_Argument> dataDictionary = sqlSyscom.GetDictionaryId("SuitDegreeID", at_Name);
            //string vlaue = "";
            //if (dataDictionary.Count > 0)
            //{
            //    return dataDictionary[0].AM_Code.ToString();
            //}
            return vlaue;
        }
        /// <summary>
        /// 根据匹配内容获取参数值
        /// </summary>
        /// <param name="matchKeyWords">匹配内容</param>
        /// <param name="originalValue">原始值</param>
        /// <returns>参数值</returns>
        public static string GetArgumentValueByMatchWords(string matchKeyWords, string originalValue)
        {
            string fieldValue = originalValue;
            matchKeyWords = Regex.Replace(matchKeyWords, @"(?<=;)\s", "", RegexOptions.Singleline);
            if (matchKeyWords != string.Empty)
            {
                fieldValue = (fieldValue == string.Empty) ? "空" : fieldValue;
                //string paternStr = RegexParseClass.GetRegexLastStr("DictMatchingA1");
                string paternStr = @"(?<=^|；|;)[^=]+(?==(?:[^=；;]*[,，]*?)(?<![\u4E00-\u9FFF\r，、][\)）]?){MatchKeyWord}[,;；])";
                string currPatern = paternStr.Replace("{MatchKeyWord}", fieldValue);
                string extractValue = Regex.Match(matchKeyWords.Replace("\r", ""), currPatern, RegexOptions.Singleline).Value.Trim(); //返回匹配到的编号值！
                if (extractValue == string.Empty && fieldValue != "空")
                {
                    //01.假如当前匹配值，满足1）未匹配成功。2）本身就是匹配字典值中的一个。则直接返回。
                    if (Regex.IsMatch(matchKeyWords, @"(?:^|;)" + originalValue + "="))
                    {
                        return originalValue;
                    }
                    //02.上述没匹配成功，则再进行其他匹配。
                    currPatern = paternStr.Replace("{MatchKeyWord}", "其他");
                    extractValue = Regex.Match(matchKeyWords, currPatern, RegexOptions.Singleline).Value;    //返回匹配到的编号值！
                    extractValue = extractValue.Replace("\r", "");//2017-09-12 ljx 添加提取出来的结果存在 ”\r\r\r内容“这样的类型值
                }
                if (extractValue == string.Empty)
                {
                    return "";
                }
                else
                {
                    return extractValue;
                }
            }
            return originalValue;
        }
    }
}
